var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
// post请求会用到
var bodyParser = require('body-parser');
require('body-parser-xml')(bodyParser);
var ejs = require('ejs');


var CommonJS = require('./common/common');
var DBConfig = require('./db/dbconfig');
var mysql = require('mysql');
var pool = mysql.createPool(DBConfig.mysql2);

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({ extended: false, limit: '1000mb' }));
// parse application/json
app.use(bodyParser.json()); // request entity too large
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.xml({
  limit: '1MB',   // Reject payload bigger than 1 MB 
  xmlParseOptions: {
    normalize: true,     // Trim whitespace inside text nodes 
    normalizeTags: true, // Transform tags to lowercase 
    explicitArray: false // Only put nodes in array if >1 
  }
}));

// 设置请求头
// application/json  接口返回json数据
// charset=utf-8 解决json数据中中文乱码
app.use("*", function(req, res, next) {
	res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Credentials", true);
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 4.2.1');
	res.writeHead(200, { "Content-Type": "application/json;charset=utf-8" });
	// PC端 接口请求记录
	var param = req.query || req.params; 
	var telno = param.telno || param.tel || '';
	var request_name = param.request_name || '';
	var create_time = CommonJS.getNowFormatDate();
	if(telno != ''){
		pool.getConnection(function(err, connection) {
			if(err){
//				console.log('链接错误');
			}
			connection.query(DBConfig.pc_request_list,[telno,request_name,create_time],function (err, results) {
				connection.release();
				if (err){
//				  	console.log('查询错误');
				}else{
//					console.log('操作成功');
				}
			})
		})
	}
	next();
});

// 验证码
var varcode = require('./routes/wx/varcode/varcode');
app.use('/', varcode);
// 登录
var login = require('./routes/wx/user/login');
app.use('/', login);
// 注册
var register = require('./routes/wx/user/register');
app.use('/', register);
// 绑定手机号
var bindtel = require('./routes/wx/user/bindtel');
app.use('/', bindtel);
// 个人中心
var me = require('./routes/wx/user/me');
app.use('/', me);
// 商品-分类
var goods_classify = require('./routes/wx/goods/goods_classify');
app.use('/', goods_classify);
// 商品-列表
var goods_list = require('./routes/wx/goods/goods_list');
app.use('/', goods_list);
// 商品-详情
var goods_detail = require('./routes/wx/goods/goods_detail');
app.use('/', goods_detail);
// 购物车
var cart = require('./routes/wx/cart/cart');
app.use('/', cart);
// 搜索历史
var hot_search = require('./routes/wx/hotsearch/hot_search');
app.use('/', hot_search);
// 商品收藏
var collection = require('./routes/wx/collection/collection');
app.use('/', collection);
// 浏览足迹
var footprint = require('./routes/wx/footprint/footprint');
app.use('/', footprint);
// 地址
var address = require('./routes/wx/address/address');
app.use('/', address);
// 订单
var order = require('./routes/wx/order/order');
app.use('/', order);
// 支付
var pay = require('./routes/wx/order/pay');
app.use('/', pay);
// 订单评价
var order_comment = require('./routes/wx/comment/comment');
app.use('/', order_comment);
// 优惠券
var coupon = require('./routes/wx/coupon/coupon2');
app.use('/', coupon);

// access_token
var access_token = require('./routes/accessToken/accessToken');
app.use('/', access_token);

// PC端

// 商品列表
var pc_goods_list = require('./routes/pc/goods');
app.use('/', pc_goods_list);
// 商品规格
var pc_goods_spec = require('./routes/pc/spec');
app.use('/', pc_goods_spec);
// 图片上传
var pc_upload = require('./routes/upload/imageupload');
app.use('/', pc_upload);
// 商品分类
var pc_classify = require('./routes/pc/classify');
app.use('/', pc_classify);
// 搜索历史
var pc_hotsearch = require('./routes/pc/hotsearch');
app.use('/', pc_hotsearch);
// 订单
var pc_order = require('./routes/pc/order');
app.use('/', pc_order);
// 登录
var pc_user = require('./routes/pc/user');
app.use('/', pc_user);
// 账户余额
var pc_balance = require('./routes/pc/balance');
app.use('/', pc_balance);
// 优惠券
var pc_coupon = require('./routes/pc/coupon2');
app.use('/', pc_coupon);
// 轮播图
var pc_banners = require('./routes/pc/banners');
app.use('/', pc_banners);
// 首页
var pc_home = require('./routes/pc/home');
app.use('/', pc_home);
// 充值
var pc_recharge = require('./routes/pc/recharge');
app.use('/', pc_recharge);




// 复制数据库中的商品
var copy_goods = require('./routes/copy/copy_goods');
app.use('/', copy_goods);
// 复制数据库中的商品评价
var copy_comment = require('./routes/copy/copy_comment');
app.use('/', copy_comment);
// 复制数据库中的商品和分类的关系
var copy_goods_classify_relation = require('./routes/copy/copy_goods_classify_relation');
app.use('/', copy_goods_classify_relation);
// 复制数据库中的商品分类
var copy_goods_classify = require('./routes/copy/copy_goods_classify');
app.use('/', copy_goods_classify);
// 复制数据库中的图片上传记录
var copy_images = require('./routes/copy/copy_images');
app.use('/', copy_images);
// 复制数据库中的订单记录
var copy_order = require('./routes/copy/copy_order');
app.use('/', copy_order);
// 复制数据库中的后台管理人员
var copy_malladmin = require('./routes/copy/copy_shiper');
app.use('/', copy_malladmin);
// 复制数据库中的用户表
var copy_account = require('./routes/copy/copy_account');
app.use('/', copy_account);

//api接口路由
//var apiRouter = require('./api/router/router');
//app.use(apiRouter);
////优惠券规则
//app.use(require('./routes/pc/couponRule'));
////优惠券
//app.use(require('./routes/pc/coupon'));
////手机端优惠券
//app.use(require('./routes/wx/coupon/coupon'));
////充值设置
//app.use(require('./routes/pc/recharge'));
////发送消息
//app.use(require('./api/message/sendMessage'));


// catch 404 and forward to error handler
// 404 错误
var errorData_404 = {
	status: '404', 
	msg: 'Not Found!',
};
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  res.end(JSON.stringify(errorData_404));
});

// 500 
var errorData_500 = {
	status: '500', 
	msg: 'Not Found!',
};
app.use(function(err, req, res, next) {
  errorData_500.msg =  err.message;
  res.end(JSON.stringify(errorData_500));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;


